package com.ruge.test.springMVC.支持json;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;

/**
 * 爱丽丝、如歌  创建于 2018/6/27 8:30
 * 说明:  TODO
 */
public class mysql树形结构测试 {
    @Test
    public void loadTree() throws Exception {
        TreeNode treeNode = this.recursiveTree(1);
        ObjectMapper mapper = new ObjectMapper();
        String mapJakcson = mapper.writeValueAsString(treeNode);
        System.out.println(mapJakcson);
    }

    /**
     * 递归算法解析成树形结构
     *
     * @param cid
     * @return
     * @author jiqinlin
     */
    public TreeNode recursiveTree(int cid) throws Exception {

        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ruge_security?serverTimezone=UTC", "root", "root");
        QueryRunner runner = new QueryRunner();
        Object[] params = {cid};

        TreeNode node = runner.query(conn, "SELECT * FROM tb_tr ee t WHERE t.cid=?", new BeanHandler<>(TreeNode.class), params);
        System.out.println("node+++"+node);
        List<TreeNode> childTreeNodes = runner.query(conn, "SELECT * FROM tb_tree t WHERE t.pid=?", new BeanListHandler<TreeNode>(TreeNode.class), params);

        for (TreeNode child : childTreeNodes
                ) {
            /**
             * 递归
             */
            TreeNode n = recursiveTree(child.getCid());
            node.getNodes().add(n);
       //     System.out.println(child);
        }
        return node;
    }
}
